//
//  ViewController.m
//  NativeDemo
//
//  Created by hank on 2020/6/20.
//  Copyright © 2020 hank. All rights reserved.
//
/**
 * FlutterMethodChannel : 调用方法(method invocation)一次通讯的
 * 以下两种都是持续通讯的!
 *      FlutterBasicMessageChannel :传递字符&半结构化的信息.
 *      FlutterEventChannel    : 用于数据流(stream)的通讯
 */

#import "ViewController.h"
#import <Flutter/Flutter.h>

@interface ViewController ()
@property(nonatomic, strong) FlutterEngine* flutterEngine;
@property(nonatomic, strong) FlutterViewController * flutterVc;
@property(nonatomic, strong) FlutterBasicMessageChannel * msgChannel;
@end

@implementation ViewController

-(FlutterEngine *)flutterEngine
{
    if (!_flutterEngine) {
        FlutterEngine * flutterEngine = [[FlutterEngine alloc] initWithName:@"hank"];
        if (flutterEngine.run) {
            _flutterEngine = flutterEngine;
        }
    }
    return _flutterEngine;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.flutterVc = [[FlutterViewController alloc] initWithEngine:self.flutterEngine nibName:nil bundle:nil];
    
    self.flutterVc.modalPresentationStyle = 0;
    
    //接收Flutter的数据
    self.msgChannel  = [FlutterBasicMessageChannel messageChannelWithName:@"messageChannel" binaryMessenger:self.flutterVc];
    
    [self.msgChannel setMessageHandler:^(id  _Nullable message, FlutterReply  _Nonnull callback) {
        NSLog(@"收到Flutter的:%@",message);
    }];
}

- (IBAction)poushFlutter:(id)sender {
    FlutterMethodChannel * methodChannel = [FlutterMethodChannel methodChannelWithName:@"one_page" binaryMessenger:self.flutterVc];
    
    [methodChannel invokeMethod:@"one" arguments:nil];
    
    [self presentViewController:self.flutterVc animated:YES completion:nil];
    
    [methodChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
        if ([call.method isEqualToString:@"exit"]) {
            [self.flutterVc dismissViewControllerAnimated:YES completion:nil];
        }
    }];
    
}


- (IBAction)pushFlutterTwo:(id)sender {
    FlutterMethodChannel * methodChannel = [FlutterMethodChannel methodChannelWithName:@"two_page" binaryMessenger:self.flutterVc];
    [methodChannel invokeMethod:@"two" arguments:nil];
    
    [self presentViewController:self.flutterVc animated:YES completion:nil];
    
    [methodChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
        if ([call.method isEqualToString:@"exit"]) {
            [self.flutterVc dismissViewControllerAnimated:YES completion:nil];
        }
    }];
    
    
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    static int a = 0;
    [self.msgChannel sendMessage:[NSString stringWithFormat:@"%d",a++]];
}

@end
